<?php
namespace app\admin\controller;

use app\common\controller\BaseController;
use app\common\repositories\users\UsersRepository;
use app\common\repositories\merchant\MerchantRepository;
use app\common\service\MembershipService;
use support\Container;
use support\Db;

/**
 * 管理后台控制器
 * 系统管理员控制台和用户管理界面
 */
class AdminController extends BaseController
{
    protected $userRepository;
    protected $merchantRepository;

    public function __construct()
    {
        $this->userRepository = new UsersRepository();
        $this->merchantRepository = new MerchantRepository();
    }

    /**
     * 管理员登录
     * @api {post} /admin/login 管理员登录
     * @apiParam {String} username 管理员用户名
     * @apiParam {String} password 密码
     */
    public function login()
    {
        $username = request()->post('username');
        $password = request()->post('password');

        if (!$username || !$password) {
            return json(['code' => 400, 'msg' => '用户名和密码不能为空']);
        }

        // 检查是否是管理员账户
        $admin = Db::name('gf_admins')
            ->where('username', $username)
            ->where('status', 1)
            ->find();

        if (!$admin || !password_verify($password, $admin['password'])) {
            return json(['code' => 401, 'msg' => '管理员用户名或密码错误']);
        }

        // 生成管理员token
        $token = md5($admin['id'] . time() . uniqid());
        
        // 更新登录信息
        Db::name('gf_admins')->where('id', $admin['id'])->update([
            'last_login_at' => date('Y-m-d H:i:s'),
            'last_login_ip' => request()->getRealIp(),
            'token' => $token
        ]);

        return json([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'admin_id' => $admin['id'],
                'username' => $admin['username'],
                'role' => $admin['role'],
                'token' => $token,
                'permissions' => json_decode($admin['permissions'], true)
            ]
        ]);
    }

    /**
     * 获取系统概览数据
     * @api {get} /admin/dashboard 系统概览
     */
    public function dashboard()
    {
        $admin = $this->checkAdminAuth();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        // 获取今日数据
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('-1 day'));

        // 用户统计
        $userStats = $this->getUserStats($today, $yesterday);
        
        // 商户统计
        $merchantStats = $this->getMerchantStats($today, $yesterday);
        
        // 应用统计
        $appStats = $this->getAppStats($today, $yesterday);
        
        // 收入统计
        $revenueStats = $this->getRevenueStats($today, $yesterday);

        return json([
            'code' => 200,
            'data' => [
                'user_stats' => $userStats,
                'merchant_stats' => $merchantStats,
                'app_stats' => $appStats,
                'revenue_stats' => $revenueStats,
                'system_info' => $this->getSystemInfo()
            ]
        ]);
    }

    /**
     * 用户管理列表
     * @api {get} /admin/users 用户管理列表
     * @apiParam {Number} page 页码
     * @apiParam {Number} limit 每页数量
     * @apiParam {String} keyword 搜索关键词
     * @apiParam {String} status 状态筛选
     * @apiParam {String} membership_type 会员类型筛选
     */
    public function users()
    {
        $admin = $this->checkAdminAuth();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $page = (int)request()->get('page', 1);
        $limit = (int)request()->get('limit', 20);
        $keyword = request()->get('keyword', '');
        $status = request()->get('status', '');
        $membershipType = request()->get('membership_type', '');

        $query = Db::name('gf_users')
            ->alias('u')
            ->leftJoin('gf_user_memberships um', 'u.id = um.user_id')
            ->leftJoin('gf_membership_plans mp', 'um.plan_type = mp.plan_type')
            ->field('u.id, u.email, u.nickname, u.avatar, u.status, u.create_at, u.last_login_at,
                    um.plan_type, um.start_date, um.end_date, um.status as membership_status,
                    mp.name as plan_name, mp.app_limit')
            ->where('u.is_del', 0);

        if ($keyword) {
            $query->where(function($q) use ($keyword) {
                $q->where('u.email', 'like', "%{$keyword}%")
                  ->whereOr('u.nickname', 'like', "%{$keyword}%");
            });
        }

        if ($status !== '') {
            $query->where('u.status', $status);
        }

        if ($membershipType) {
            $query->where('um.plan_type', $membershipType);
        }

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        // 处理会员信息
        foreach ($list as &$user) {
            $user['membership_info'] = $this->formatMembershipInfo($user);
            unset($user['plan_type'], $user['start_date'], $user['end_date'], 
                  $user['membership_status'], $user['plan_name'], $user['app_limit']);
        }

        return json([
            'code' => 200,
            'data' => [
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 商户管理列表
     * @api {get} /admin/merchants 商户管理列表
     * @apiParam {Number} page 页码
     * @apiParam {Number} limit 每页数量
     * @apiParam {String} keyword 搜索关键词
     * @apiParam {String} status 状态筛选
     */
    public function merchants()
    {
        $admin = $this->checkAdminAuth();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $page = (int)request()->get('page', 1);
        $limit = (int)request()->get('limit', 20);
        $keyword = request()->get('keyword', '');
        $status = request()->get('status', '');

        $query = Db::name('gf_merchants')
            ->field('id, company_name, contact_name, email, phone, status, 
                    created_at, last_login_at, verified_at, daily_requests_limit,
                    apps_limit, storage_limit')
            ->where('status', '!=', 'deleted');

        if ($keyword) {
            $query->where(function($q) use ($keyword) {
                $q->where('company_name', 'like', "%{$keyword}%")
                  ->whereOr('contact_name', 'like', "%{$keyword}%")
                  ->whereOr('email', 'like', "%{$keyword}%");
            });
        }

        if ($status) {
            $query->where('status', $status);
        }

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        // 获取商户的应用数量
        foreach ($list as &$merchant) {
            $merchant['app_count'] = Db::name('gf_apps')
                ->where('user_id', $merchant['id'])
                ->where('is_del', 0)
                ->count();
            
            $merchant['quota_usage'] = $this->getMerchantQuotaUsage($merchant['id']);
        }

        return json([
            'code' => 200,
            'data' => [
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 应用管理列表
     * @api {get} /admin/apps 应用管理列表
     * @apiParam {Number} page 页码
     * @apiParam {Number} limit 每页数量
     * @apiParam {String} keyword 搜索关键词
     * @apiParam {String} status 状态筛选
     * @apiParam {Number} user_id 用户ID筛选
     */
    public function apps()
    {
        $admin = $this->checkAdminAuth();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $page = (int)request()->get('page', 1);
        $limit = (int)request()->get('limit', 20);
        $keyword = request()->get('keyword', '');
        $status = request()->get('status', '');
        $userId = request()->get('user_id', '');

        $query = Db::name('gf_apps')
            ->alias('a')
            ->leftJoin('gf_users u', 'a.user_id = u.id')
            ->field('a.id, a.name, a.appkey, a.package_name, a.status, a.create_at, a.update_at,
                    u.email as user_email, u.nickname as user_nickname')
            ->where('a.is_del', 0);

        if ($keyword) {
            $query->where(function($q) use ($keyword) {
                $q->where('a.name', 'like', "%{$keyword}%")
                  ->whereOr('a.appkey', 'like', "%{$keyword}%")
                  ->whereOr('a.package_name', 'like', "%{$keyword}%");
            });
        }

        if ($status !== '') {
            $query->where('a.status', $status);
        }

        if ($userId) {
            $query->where('a.user_id', $userId);
        }

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        // 获取应用的统计数据
        foreach ($list as &$app) {
            $app['stats'] = $this->getAppDetailStats($app['appkey']);
        }

        return json([
            'code' => 200,
            'data' => [
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 系统设置
     * @api {get} /admin/settings 获取系统设置
     */
    public function settings()
    {
        $admin = $this->checkAdminAuth();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $settings = Db::name('gf_settings')->column('value', 'key');
        
        return json([
            'code' => 200,
            'data' => [
                'site_settings' => $settings,
                'membership_plans' => $this->getMembershipPlans(),
                'system_status' => $this->getSystemStatus()
            ]
        ]);
    }

    /**
     * 更新系统设置
     * @api {post} /admin/settings/update 更新系统设置
     * @apiParam {Object} settings 设置对象
     */
    public function updateSettings()
    {
        $admin = $this->checkAdminAuth();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $settings = request()->post('settings', []);
        
        if (empty($settings)) {
            return json(['code' => 400, 'msg' => '设置不能为空']);
        }

        try {
            foreach ($settings as $key => $value) {
                Db::name('gf_settings')->where('key', $key)->update([
                    'value' => is_array($value) || is_object($value) ? json_encode($value) : $value,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            return json(['code' => 200, 'msg' => '设置更新成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '设置更新失败: ' . $e->getMessage()]);
        }
    }

    // 私有辅助方法
    private function checkAdminAuth()
    {
        $token = request()->header('X-Admin-Token') ?? request()->get('admin_token');
        
        if (!$token) {
            return false;
        }

        $admin = Db::name('gf_admins')
            ->where('token', $token)
            ->where('status', 1)
            ->find();

        return $admin ?: false;
    }

    private function getUserStats($today, $yesterday)
    {
        $todayUsers = Db::name('gf_users')
            ->where('create_at', '>=', $today . ' 00:00:00')
            ->count();
        
        $yesterdayUsers = Db::name('gf_users')
            ->whereBetween('create_at', [$yesterday . ' 00:00:00', $yesterday . ' 23:59:59'])
            ->count();

        $totalUsers = Db::name('gf_users')->where('is_del', 0)->count();
        $activeUsers = Db::name('gf_users')->where('status', 1)->where('is_del', 0)->count();

        return [
            'today_new' => $todayUsers,
            'yesterday_new' => $yesterdayUsers,
            'total' => $totalUsers,
            'active' => $activeUsers,
            'growth_rate' => $yesterdayUsers > 0 ? round((($todayUsers - $yesterdayUsers) / $yesterdayUsers) * 100, 2) : 0
        ];
    }

    private function getMerchantStats($today, $yesterday)
    {
        $todayMerchants = Db::name('gf_merchants')
            ->where('created_at', '>=', $today . ' 00:00:00')
            ->count();
        
        $yesterdayMerchants = Db::name('gf_merchants')
            ->whereBetween('created_at', [$yesterday . ' 00:00:00', $yesterday . ' 23:59:59'])
            ->count();

        $totalMerchants = Db::name('gf_merchants')->where('status', '!=', 'deleted')->count();
        $activeMerchants = Db::name('gf_merchants')->where('status', 'active')->count();

        return [
            'today_new' => $todayMerchants,
            'yesterday_new' => $yesterdayMerchants,
            'total' => $totalMerchants,
            'active' => $activeMerchants,
            'growth_rate' => $yesterdayMerchants > 0 ? round((($todayMerchants - $yesterdayMerchants) / $yesterdayMerchants) * 100, 2) : 0
        ];
    }

    private function getAppStats($today, $yesterday)
    {
        $todayApps = Db::name('gf_apps')
            ->where('create_at', '>=', $today . ' 00:00:00')
            ->count();
        
        $yesterdayApps = Db::name('gf_apps')
            ->whereBetween('create_at', [$yesterday . ' 00:00:00', $yesterday . ' 23:59:59'])
            ->count();

        $totalApps = Db::name('gf_apps')->where('is_del', 0)->count();
        $activeApps = Db::name('gf_apps')->where('status', 1)->where('is_del', 0)->count();

        return [
            'today_new' => $todayApps,
            'yesterday_new' => $yesterdayApps,
            'total' => $totalApps,
            'active' => $activeApps,
            'growth_rate' => $yesterdayApps > 0 ? round((($todayApps - $yesterdayApps) / $yesterdayApps) * 100, 2) : 0
        ];
    }

    private function getRevenueStats($today, $yesterday)
    {
        $todayRevenue = Db::name('gf_balance_logs')
            ->where('type', 'recharge')
            ->where('create_at', '>=', $today . ' 00:00:00')
            ->sum('amount');
        
        $yesterdayRevenue = Db::name('gf_balance_logs')
            ->where('type', 'recharge')
            ->whereBetween('create_at', [$yesterday . ' 00:00:00', $yesterday . ' 23:59:59'])
            ->sum('amount');

        $totalRevenue = Db::name('gf_balance_logs')->where('type', 'recharge')->sum('amount');

        return [
            'today' => $todayRevenue,
            'yesterday' => $yesterdayRevenue,
            'total' => $totalRevenue,
            'growth_rate' => $yesterdayRevenue > 0 ? round((($todayRevenue - $yesterdayRevenue) / $yesterdayRevenue) * 100, 2) : 0
        ];
    }

    private function formatMembershipInfo($user)
    {
        if (!$user['plan_type']) {
            return [
                'has_membership' => false,
                'plan_name' => '无会员',
                'status' => 'none',
                'expiry_date' => null
            ];
        }

        $isExpired = strtotime($user['end_date']) < time();
        $daysLeft = ceil((strtotime($user['end_date']) - time()) / 86400);

        return [
            'has_membership' => true,
            'plan_name' => $user['plan_name'],
            'plan_type' => $user['plan_type'],
            'status' => $user['membership_status'],
            'expiry_date' => $user['end_date'],
            'is_expired' => $isExpired,
            'days_left' => max(0, $daysLeft),
            'app_limit' => $user['app_limit']
        ];
    }

    private function getMerchantQuotaUsage($merchantId)
    {
        $merchant = Db::name('gf_merchants')->where('id', $merchantId)->find();
        
        return [
            'daily_requests' => [
                'used' => 0, // 需要实现实际统计
                'limit' => $merchant['daily_requests_limit'] ?? 10000
            ],
            'apps' => [
                'used' => Db::name('gf_apps')->where('user_id', $merchantId)->where('is_del', 0)->count(),
                'limit' => $merchant['apps_limit'] ?? 10
            ],
            'storage' => [
                'used' => 0, // 需要实现实际统计
                'limit' => $merchant['storage_limit'] ?? 1073741824 // 1GB
            ]
        ];
    }

    private function getAppDetailStats($appkey)
    {
        return [
            'total_clicks' => Db::name('gf_apps_web')->where('appkey', $appkey)->count(),
            'total_installs' => Db::name('gf_apps_apps')->where('appkey', $appkey)->count(),
            'total_events' => Db::name('gf_apps_event')->where('appkey', $appkey)->count(),
            'today_clicks' => Db::name('gf_apps_web')->where('appkey', $appkey)->where('create_at', '>=', date('Y-m-d'))->count(),
            'today_installs' => Db::name('gf_apps_apps')->where('appkey', $appkey)->where('create_at', '>=', date('Y-m-d'))->count(),
            'today_events' => Db::name('gf_apps_event')->where('appkey', $appkey)->where('create_at', '>=', date('Y-m-d'))->count()
        ];
    }

    private function getMembershipPlans()
    {
        return Db::name('gf_membership_plans')
            ->where('is_active', 1)
            ->order('price', 'asc')
            ->select();
    }

    private function getSystemInfo()
    {
        return [
            'php_version' => PHP_VERSION,
            'mysql_version' => Db::query('SELECT VERSION() as version')[0]['version'],
            'server_time' => date('Y-m-d H:i:s'),
            'memory_usage' => memory_get_usage(true) / 1024 / 1024 . ' MB',
            'disk_usage' => $this->getDiskUsage()
        ];
    }

    private function getDiskUsage()
    {
        $total = disk_total_space('.');
        $free = disk_free_space('.');
        $used = $total - $free;
        
        return [
            'total' => round($total / 1073741824, 2) . ' GB',
            'used' => round($used / 1073741824, 2) . ' GB',
            'free' => round($free / 1073741824, 2) . ' GB',
            'percentage' => round(($used / $total) * 100, 2) . '%'
        ];
    }
}